package org.springblade.gateway.predicates;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * AgeRoutePredicateFactory
 * 自定义路由断言工厂类
 * http://helloWorld.com
 *
 * @author yofi
 * @date 2021/4/15 16:34
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

	public AgeRoutePredicateFactory() {
		super(Config.class);
	}

	/**
	 * 读取配置文件中参数，给他赋值到配置类中的属性上
	 *
	 * @return
	 */
	@Override
	public List<String> shortcutFieldOrder() {
		//位置顺序必须和配置文件中的顺序相同
		return Arrays.asList("minAge", "maxAge");
	}

	/**
	 *
	 * @param config
	 * @return
	 */
	@Override
	public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
		return new GatewayPredicate() {
			@Override
			public boolean test(ServerWebExchange exchange) {

				//接受前台传入的age参数
				String ageStr = exchange.getRequest().getQueryParams().getFirst("age");
				//1、先判断是否为空
				if (StringUtils.isNotEmpty(ageStr)) {
					//2、如果不为空，再进行路由判断
					Integer age = Integer.parseInt(ageStr);
					if (age > config.getMinAge() && age < config.getMaxAge()) {
						return true;
					} else {
						return false;
					}
				}
				return false;
			}
		};
	}

	/**
	 * 配置
	 */
	public static class Config {

		private int minAge;
		private int maxAge;

		public Config() {
		}

		public int getMinAge() {
			return minAge;
		}

		public void setMinAge(int minAge) {
			this.minAge = minAge;
		}

		public int getMaxAge() {
			return maxAge;
		}

		public void setMaxAge(int maxAge) {
			this.maxAge = maxAge;
		}
	}
}
